﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using ATM_Pro.Module;

using System.Threading;
using System.Collections;
using ATM_Pro.Query;
using ATM_Pro.Public;
using System.Drawing;

namespace ATM_Pro
{
    public class TransPacketHandle : IPacketHandler
    {
       

        public TransPacketHandle()
        {
            tpb = new TransPacketBean();
            
        }

        private TransPacketBean tpb = null;
        public TransPacketBean TransPackBean
        {
            get { return tpb; }
        }
        public event ImageDataChangeHandle DataChange;

        #region IPacketHandler Members

        public bool CanHandle(byte[] bytes)
        {
            return (IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 8)) == 3);
        }

        string prePath = "";
        string secPath = "";
        int preMinute = 0;
        int ocount = 0;
        int fcount = 0;
        int handleCount = 0;
        public void Handle(byte[] bytes)
        {
            DateTime transTime;  
            string cardId = "";
            int packType = -1;
            int atmId = -1;
            int camId = -1;
            int addId = -1;
            int originImageLen = -1;
            int faceImageLen = -1;
            int length = -1;

            length = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 4));//数据长度  first
            if (length+8 == bytes.Length)
            {
                packType = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 8));
                cardId = System.Text.Encoding.Default.GetString(bytes, 12, 32);
                atmId = bytes[44];
                camId = bytes[45];
                addId = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 46));
                transTime = GetLocalTime(IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 48)));

                originImageLen = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 52));//原始图像长度
                faceImageLen = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 56));//人脸截图长度
                if (originImageLen < 0 || faceImageLen <0) return;

                tpb.AtmBean = new ATM(atmId, Enum.GetName(typeof(AtmAddress), addId), addId, new Camera(camId, Enum.GetName(typeof(CameraNumber), camId), PacketType.TradeMessage));
                tpb.CardId = cardId.Substring(0, cardId.IndexOf("\0"));
                tpb.TransTime = transTime;
                tpb.FaceImg = bytes;
                tpb.OriginImgLength = originImageLen;
                tpb.FaceImgLength = faceImageLen;
                tpb.PackLength = length;

                if (originImageLen < 0 || faceImageLen < 0) return;

                string path = ImageHandle.GenerateSavePath(tpb.AtmBean, tpb.TransTime, ocount++, 0);
                tpb.OriginImgPath = path;

                MemoryStream ms = new MemoryStream(bytes, 60, originImageLen);
                Image img = System.Drawing.Image.FromStream(ms);
                FileStream fs = File.OpenWrite(path);
                img.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
                fs.Close();
                ms.Dispose();
                

                path = ImageHandle.GenerateSavePath(tpb.AtmBean, tpb.TransTime, fcount++, 1);
                tpb.Path = path;

                MemoryStream faceData = new MemoryStream(bytes, 60 + originImageLen, faceImageLen);
                Image faceimg = System.Drawing.Image.FromStream(faceData);
                FileStream faceFs = File.OpenWrite(path);
                faceimg.Save(faceFs, System.Drawing.Imaging.ImageFormat.Jpeg);
                faceFs.Close();
                faceData.Close();

                QeuryInfoHandle handle = new QeuryInfoHandle();
                handle.Tpb = tpb;
                Thread thhandle = new Thread(new ParameterizedThreadStart(handle.InsertTransinfo));
                thhandle.Start();

                ms.Close();
                ms.Dispose();
                img.Dispose();

                #region  人脸比对
                //if (File.Exists(path))
                //{
                //    bool temp = false;
                //    //人脸比对
                //    if (prePath != "" && secPath != "")
                //    {
                //        Thread.Sleep(500);
                //        double match = MatchFace.StartMacth(prePath, secPath, ref temp);
                //        if (temp)
                //        {
                //            if (match < 0.6)
                //            {
                //                OnDataChanged(this, new DataChangeEventArgs(this.GetType().Name));
                //            }
                //        }
                //        prePath = secPath;
                //        secPath = path;
                //    }
                //    else if (prePath != "" && secPath == "")
                //    {
                //        double match = MatchFace.StartMacth(prePath, path, ref temp);
                //        if (temp)
                //        {
                //            if (match < 0.6)
                //            {
                //                OnDataChanged(this, new DataChangeEventArgs(this.GetType().Name));
                //            }
                //        }
                //        secPath = path;
                //    }
                //    else if (prePath == "" && secPath == "")
                //    {
                //        OnDataChanged(this, new DataChangeEventArgs(this.GetType().Name));
                //        prePath = path;
                //    }
                //}
                #endregion

                //压缩视频
                if (preMinute != transTime.Minute)
                {
                    ocount = fcount = 0;
                    //if (handleCount == 1)
                    //{
                    //    IVideoCompression icom = new VideoHandle(path, preMinute, img.Width, img.Height);
                    //    if (!icom.HasVideo(PacketType.TradeMessage))
                    //    {
                    //        Thread th = new Thread(new ParameterizedThreadStart(icom.CompressionImage));
                    //        th.Start();
                    //    }
                    //}
                    //handleCount = 1;
                }
                preMinute = transTime.Minute;

                OnDataChanged(this, new DataChangeEventArgs(this.GetType().Name));

            }
        }

        #endregion

        protected void OnDataChanged(object sender, DataChangeEventArgs e)
        {
            if (this.DataChange != null)
            {
                DataChange(sender, e);
            }
        }

        protected DateTime GetLocalTime(int second)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(second).ToLocalTime();
        }
    }
}
